package com.higgins.eventtracking.server;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.higgins.eventtracking.server.dataModel.Asset;
import com.higgins.eventtracking.server.dataModel.HealthAlert;
import com.higgins.eventtracking.server.dataModel.InventoryAlert;

@SuppressWarnings("serial")
public class CheckForInventoryEventServlet extends HttpServlet	{
	private static final Logger log = Logger.getLogger(CheckForInventoryEventServlet.class.getName());
	private DietTrackingDataService dietTrackingDataService = new DietTrackingDataService();

	public void doGet(HttpServletRequest req, HttpServletResponse resp)	throws IOException	{
		log.info("CheckForHealthEventServlet is running!!");

		dietTrackingDataService.openPersistenceManager();
		checkInventoryEvents();
		
		dietTrackingDataService.closePersistenceManager();
	}
	private void checkInventoryEvents()	{
		log.info("CheckForInventoryEventServlet is running checkInventoryEvents() method!!");
		List<InventoryAlert> inventoryAlerts = dietTrackingDataService.retrieveInventoryAlerts();
		log.info("There are " + inventoryAlerts.size() + " inventory alerts to check!!");
		for (InventoryAlert inventoryAlert:inventoryAlerts)	{
			log.info("Checking " + inventoryAlert.getName() + " alert!!");
			String message = dietTrackingDataService.sendInventoryAlert(inventoryAlert);
			if (message!=null)	{
				log.info("Sending email for " + message + " alert!!");
				sendEmail(message);
			} 
		}
	}

	private void sendEmail(String message)	{
		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        String msgBody = message;

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("pshiggins@gmail.com", "Patrick Higgins"));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress("pshiggins@gmail.com", "Patrick Higgins"));
            msg.setSubject(message);
            msg.setText(msgBody);
            Transport.send(msg);

        } catch (Exception e) {

        }
	}
}
